package br.ufc.great.dtxtester;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Vector;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import br.ufc.great.dtxtester.operation.QueryOperation;

public class Catalog {

	private Document document;
	
	public Catalog(String fileName) throws IOException {
		SAXBuilder saxBuilder = new SAXBuilder();
		String appPath = System.getProperty("user.dir");
		if (appPath.endsWith("bin"))
			appPath = appPath.substring(0, appPath.length() - "bin".length());
		appPath += System.getProperty("file.separator");
		File file = new File(appPath + fileName);
	    try {
			document = saxBuilder.build(file);
		}
	    catch (JDOMException e) {
			throw new IOException(e.getMessage());
		}
	    catch (IOException e) {
			throw e;
		}
		
	}
	
	public String getQuerySites(String id) {
		Element catalogRoot = document.getRootElement();
	    List queryList = catalogRoot.getChild("queries").getChildren();
	    for (int i = 0; queryList != null && i < queryList.size(); i++) {
	    	Element item = (Element) queryList.get(i);
	    	String itemId = item.getAttributeValue("id");
	    	if (itemId.equalsIgnoreCase(id))
	    		return item.getAttributeValue("sites").trim();
	    }
	    return null;
	}
	
	public String getInsertSites(String id) {
		Element catalogRoot = document.getRootElement();
	    List insertList = catalogRoot.getChild("inserts").getChildren();
	    for (int i = 0; insertList != null && i < insertList.size(); i++) {
	    	Element item = (Element) insertList.get(i);
	    	String itemId = item.getAttributeValue("id");
	    	if (itemId.equalsIgnoreCase(id))
	    		return item.getAttributeValue("sites").trim();
	    }
	    return null;
	}
	
	public Vector<Site> getSites() {
	    Vector<Site> sites = new Vector<Site>();
		Element catalogRoot = document.getRootElement();
	    List sitesList = catalogRoot.getChild("sites").getChildren();
	    for (int i = 0; sitesList != null && i < sitesList.size(); i++) {
	    	Element item = (Element) sitesList.get(i);
	    	String id = item.getAttributeValue("id");
	    	String host = item.getAttributeValue("host").trim();
	    	int port = Integer.parseInt(item.getAttributeValue("port").trim());
			sites.add(new Site(id, host, port));
	    }
		return sites;
	}
	
}
